package com.tracking.application.listeners;

import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;


/**
 * Created with IntelliJ IDEA.
 * User: Kamil.O
 * Description: Listener special for tabs in seconds activity
 * Date: 18.11.13
 * Time: 23:01
 */
public class ActionBarTabListener<T extends Fragment> implements ActionBar.TabListener {

    private Fragment mFragment;
    private final Activity mActivity;
    private final String mTag;
    private final Class<T> mClass;

    public ActionBarTabListener(Activity activity, String tag, Class<T> clz) {
        this.mActivity = activity;
        this.mTag = tag;
        this.mClass = clz;
    }

    /**
     * Initialize and add the fragment to our activity if it doesn't exist
     * If it exists, we simply attach to it.
     * @param tab
     * @param ft
     */
    @Override
    public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
        if (mFragment == null) {
            mFragment = Fragment.instantiate(mActivity, mClass.getName());
            ft.add(android.R.id.content, mFragment, mTag);

        } else {
            ft.attach(mFragment);
        }
    }

    /**
     * Tab is unselected
     * Detach the fragment because it shouldn't be displayed.
     *
     * @param tab
     * @param ft
     */
    @Override
    public void onTabUnselected(ActionBar.Tab tab, android.app.FragmentTransaction ft) {
        if (mFragment != null) {
            ft.detach(mFragment);
        }
    }

    @Override
    public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {

    }

}
